package com.dashu.device.netty.handler;

import com.dashu.base.redis.JedisUtil;
import com.dashu.base.redis.RedisLiveKeyConstants;
import com.dashu.device.netty.ipml.HFServerImpl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;

import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

import static com.dashu.device.container.HFContainer.HFonlineObj;
import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;


/**
 * Created by lz on 2021/02/22
 */
@Slf4j
public class HFServerHandler extends ChannelInboundHandlerAdapter {


    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }

    }

    /*
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道已激活！");
    }

    /*
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
        log.info("CloudServerHandler.exceptionCaught:" + ctx.channel().localAddress().toString() + " 通道不活跃！");
        // 关闭流
        if (JedisUtil.hexists(RedisLiveKeyConstants.ON_LINE, HFonlineObj.get(ctx)))
            JedisUtil.hdel(RedisLiveKeyConstants.ON_LINE, HFonlineObj.get(ctx));
        HFonlineObj.remove(ctx);
    }


    /**
     * 功能：服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("异常信息：\r\n" + cause.toString());
        log.error("CloudServerHandler.exceptionCaught", cause);
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
        log.info("CloudServerHandler.exceptionCaught:" + ctx.channel().localAddress().toString() + " 通道不活跃！");
        // 关闭流
        HFonlineObj.remove(ctx);
        if (JedisUtil.hexists(RedisLiveKeyConstants.ON_LINE, HFonlineObj.get(ctx)))
            JedisUtil.hdel(RedisLiveKeyConstants.ON_LINE, HFonlineObj.get(ctx));

    }

    /**
     * 判断客户端是否掉线
     *
     * @param deviceUUID
     * @return
     */
    public static ChannelHandlerContext isConnect(String deviceUUID) {
//        CtxBean deviceInfo = cqQueue.get(deviceUUID);
//        if (deviceInfo == null)
//            return null;
//        ChannelHandlerContext ctx = deviceInfo.getCtx();
//        if (ctx != null && ctx.channel().isActive() && ctx.channel().isOpen())
//            return ctx;
//        else
        return null;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.debug("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        // 返回应答消息
        String mes = ((TextWebSocketFrame) frame).text();
//        System.out.println(mes);
//        log.info("服务端收到：" + mes);
        TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
                + ctx.channel().id() + "：" + mes);
        new HFServerImpl(mes, ctx);
    }

    /**
     * 唯一的一次http请求，用于创建websocket
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:8076/websocket", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 拒绝不合法的请求，并返回错误信息
     */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if (!isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
}